﻿using System;
using System.Collections.Generic;
using System.Net;
using Business;

public partial class Pages_Authen : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(IsPostBack) return;
        var denies = new Denies { IP = Request.UserHostAddress }.DeniesGetByDeniesIP();
        if(denies ==null || denies.Access==0)
        {
            btnLogin.Visible = false;
            Config.Message(Page, Resources.Resource.AccessDenies, Resources.Resource.Warning);
            return;
        }
    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        txtPassword.Attributes.Add("value", txtPassword.Text);
        if (string.IsNullOrEmpty(txtPassword.Text) || txtPassword.Text.Length < 6)
        {
            txtPassword.Focus();
            Config.Message(Page, Resources.Resource.PaswordInvalid, Resources.Resource.Warning);
            return;
        }
        var user = new Users().Authentication(txtUserName.Text,Business.Security.Security.MD5Encrypt(txtPassword.Text), Request.UserHostAddress, false);
        if (user == null || user.UserID <= 0)
        {
            txtPassword.Focus();
            Config.Message(Page, Resources.Resource.UsersOrPasswordIncorrect, Resources.Resource.Warning);
            return;
        }
        if (!user.IsActive)
        {
            txtPassword.Focus();
            Config.Message(Page, Resources.Resource.AccountNotActiveOrBlock, Resources.Resource.Warning);
            return;
        }
        Session[SessionManager.SessionUserid] = user.UserID;
        Session[SessionManager.SessionUserName] = user.UserName;
        Session[SessionManager.SessionFunctions] = new Functions().FunctionsGetByUserId(user.UserID);
        var list = (List<Functions>)Session[SessionManager.SessionFunctions];
        var tabs = list.FindAll(f => f.FatherID == 0);
        tabs.Sort((f1, f2) => f1.Order.CompareTo(f2.Order));
        var firsmenu = list.FindAll(f => f.FatherID == tabs[0].FunctionID);
        firsmenu.Sort((f1, f2) => f1.Order.CompareTo(f2.Order));
        Response.Redirect(Config.ApplicationUrl + tabs[0].FunctionID + "/" + firsmenu[0].FunctionID + "/admin.html");
    }
}
